<template>
  <div>
    <a-modal :title="title" :visible="visible" class="large-modal" @ok="handleOk" ok-text="选中提交" @cancel="$emit('update:visible', false)">
      <a-row v-loading="loading">
        <!-- <a-col :span="6">
            <a-tree
              style="height: 400px; overflow: auto"
              :selected-keys.sync="selectedKeys"
              :replace-fields="replaceFields"
              :tree-data="orgTreeData"
              @select="getOrgPerson"
            />
          </a-col> -->
        <!-- <a-col :span="1" /> -->
        <a-col :span="24">
          <a-form-model :model="form" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="人员姓名">
                  <BaseInput v-model="form.name" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="性别">
                  <a-select v-model="form.sex" placeholder="请选择">
                    <a-select-option :key="0" :value="0">男</a-select-option>
                    <a-select-option :key="1" :value="1">女</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-top:5px">
                <a-row>
                  <a-col :span="8" push="1">
                    <a-button type="primary" @click="search(form)">
                      查询
                    </a-button>
                  </a-col>
                  <a-col :span="8" pull="2" @click="reset">
                    <a-button>
                      重置
                    </a-button>
                  </a-col>
                  <a-col :span="8" pull="5">
                    <a-button type="primary" @click="showAddModal('add')">
                      添加外部人员
                    </a-button>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form-model>

          <a-row>
            <a-tag v-for="(item, index) of personList" :key="item.id" class="mb20p" :closable="personList.length > 1 ? true : false" @close="removePerson($event, index,item)">
              {{ item.name }}
            </a-tag>
          </a-row>
          <div></div>
          <b-table
            ref="table"
            :columns="columns"
            :select-config="{ use: mode !== 'multiple', type: 'checkbox', rowKey: 'userId' }"
            :scroll="{ y: 260 }"
            :request="loadData"
            :page-keys="['pageNumber', 'pageSize', 'totalSize']"
            :row-selection="rowSelection"
            row-key="id"
          >
            <!-- <template v-if="mode === 'multiple'" slot="action" slot-scope="text, record">
              <a @click="option(record)">{{ optionText(record) }}</a>
            </template> -->
          </b-table>
        </a-col>
      </a-row>
    </a-modal>
    <addModal :visible.sync="addModalVisible" :modal-type="addModalType" :editId="editId" @submitForm="search" />
  </div>
</template>

<script>
import { getCustOrgTree, getStaff } from '@/api/subassembly/TreeSelectOrganization'
// import { getOuterEmployeeList } from '@/api/commons'
import { getOuterEmployeeList } from '@/api/science'
import addModal from './addmodal'
import user from '@/store/modules/user'

export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      required: false
    },
    title: {
      type: String,
      default: () => '添加参与人'
    },
    mode: {
      type: String,
      default: ''
    },
    showAdd: {
      type: Boolean,
      default: () => false
    },
    orgQuery: {
      type: Object,
      default: () => null
    },
    orgId: {
      type: String,
      default: () => ''
      // default: () => '06bcbdacb4374523bdaf66586c45f749'
    },
    needData: {
      type: Boolean,
      default: () => true
    },
    maxSelectLength: {
      type: Number,
      default: () => null
    },
    //主键
    primaryKey: {
      type: String,
      default: 'id'
    }
  },

  data() {
    return {
      columns: [
        {
          title: '名称',
          dataIndex: 'name'
        },
        {
          title: '性别',
          dataIndex: 'sex'
        },
        {
          title: '电话号码',
          dataIndex: 'phone'
        },
        {
          title: '职务',
          dataIndex: 'jobTitle'
        },
        {
          title: '单位',
          dataIndex: 'unit'
        },
        {
          title: '最高学历',
          dataIndex: 'education'
        },
        {
          title: '职称',
          dataIndex: 'title'
        }
        // {
        //   title: '操作',
        //   width: '100px',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      form: {
        name: '',
        sex: ''
      },
      editId: null,
      queryParam: {},
      addModalType: 'add',
      loadData: parameter => {
        setTimeout(async () => {
          let tableData = []
          this.$refs.table.tableData.forEach((item,index) => {
            this.personList.forEach(sub => {
              if (item.id === sub.id) {
                tableData.push(item)
                this.selectedRowKeys.push(item.id)
              }
            })
          })
          
          this.selectedRows = this.$clone(tableData)
           this.difflist = []
          if(tableData.length>0){  
            this.difflist = this.personList.filter(item1 => tableData.findIndex(item2 => item2.id === item1.id) === -1);
          }else{
            this.difflist = [...this.personList]
          }
        }, 1000)
        let that = this
        let requestParameters = Object.assign({}, parameter, that.queryParam)
        requestParameters.pageNo = requestParameters.pageNumber
        return getOuterEmployeeList(requestParameters).then(res => {
          return res
        })
      },

      isAdd: true,
      content: undefined,
      loading: false,

      selectedKeys: [],
      orgTreeData: [],
      replaceFields: {
        children: 'children',
        title: 'label',
        key: 'id'
      },
      selectPersons: [],
      selectedRowKeys: [],
      selectedRows: [],
      addModalVisible: false,
      personList:this.list,//已有人员数组
      difflist:[],
    }
  },
  components: {
    addModal
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          this.personList = [...selectedRows,...this.difflist]
          console.log('this.selectedRowKeys', this.selectedRowKeys)
        }
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        setTimeout(async () => {

          this.$refs.table.getData(null, true)
          this.loading = true
          let res = await getCustOrgTree(
            this.orgQuery
              ? this.orgQuery
              : {
                  baseOrgType: 0, // 是否基础组织 0否 1是
                  containVirtual: 0 //是否包含虚拟组织 0包含 1 不包含
                }
          )
          this.loading = false
          if (res.data && res.data.length > 0) {
            this.orgTreeData = res.data
            if (this.orgId) {
              this.recursion(this.orgTreeData, null)
            }
            this.selectedKeys = [this.orgTreeData[0].id]
            this.$refs.table.getData(null, true)
          }
        }, 1000)
      } else {
        this.selectedRows = []
        this.queryParam = {}
        this.content = ''
      }
    }
  },
  methods: {
    //查询
    search(value) {
      // 赋值表单
      if (value) {
        this.queryParam = value
      }
      this.$refs.table.getData(null, true)
    },
    //重置
    reset() {
      this.form.name = ''
      this.form.sex = ''
      this.$refs.table.getData(null, true)
    },
    // 提交表单
    submitForm(e) {
      let that = this
      that.$confirm({
        title: '提示',
        content: '确认添加？',
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return addSciencesList(e).then(res => {
            if (res.code == 200 || res.data.code == 200) {
              that.$message.success('添加成功！')
              that.$refs.table.getData(null, true)
            }
          })
        }
      })
    },
    // 头部搜索
    search(value) {
      // 赋值表单
      if (value) {
        this.queryParam = value
      }
      this.$refs.table.getData(null, true)
    },
    showAddModal(type, id = null) {
      this.addModalVisible = true
      this.addModalType = type
      this.editId = id
    },
    recursion(items, parent) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i]
        if (item.id === this.orgId) {
          this.orgTreeData = [item]
        } else {
          if (item.children) {
            this.recursion(item.children, item)
          }
        }
      }
    },
    removePerson(e, index,item) {
      e && e.preventDefault()
      // let delData = this.selectedRows[index]
      // this.selectedRows.splice(index, 1)
      // this.selectedRowKeys.splice(index, 1)
      this.selectedRows= this.selectedRows.filter(i => i.id !== item.id)
      this.selectedRowKeys = this.selectedRowKeys.filter(i => i !== item.id)
      this.personList= this.personList.filter(i => i.id !== item.id)
      this.$forceUpdate()
      console.log('this.selectedRowKeysthis.selectedRowKeys', this.selectedRowKeys)
    },
    optionText(record) {
      let res = this.selectPersons.find(v => v[this.primaryKey] === record[this.primaryKey])
      return res ? '删除' : '添加'
    },
    option(record) {
      if (this.mode !== 'multiple') {
        this.selectPersons = []
      }
      let resIndex = this.selectPersons.findIndex(v => v[this.primaryKey] === record[this.primaryKey])
      if (resIndex !== -1) {
        this.removePerson(null, resIndex)
      } else {
        this.selectPersons.push(record)
      }
    },
    handleOk(e) {
      if (this.mode !== 'single' && this.maxSelectLength !== null) {
        if (this.selectPersons.length > this.maxSelectLength) {
          return this.$noticeWarning(`最多可选中${this.maxSelectLength}人`)
        }
      }
      this.personList.map(v => {
        v.orgId = this.selectedKeys[0]
      })
      this.$emit('update:visible', false)
      this.$emit('update:completeEmployeeExternal', this.personList)
      this.$emit('getSelectPerson', this.personList)
    },
    getOrgPerson(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.onSearch()
    },
    getOutside() {},
    onSearch() {
      this.queryParam.key = this.content
      this.$refs.table.getData(null, true)
    }
  }
}
</script>

<style lang="less" scoped></style>
